package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.DishNameRepeatException;
import com.sky.mapper.*;
import com.sky.result.PageBean;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.service.SetmealService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;//菜品口味
    @Autowired
    SetmealMapper setmealMapper;
    @Autowired
    SetmealDishMapper setmealDishMapper;
    @Autowired
    SetmealService setmealService;
    @Autowired
    RedisTemplate redisTemplate;


    /**
     * 条件查询菜品和口味
     *
     * @param
     * @return
     */
    public List<DishVO> listWithFlavor(Long canary_id) {

//        //添加到redis中进行模糊查询
//        //设置key
//        String key = "dish_" + canary_id;
//        //查询redis是否有
//        List<DishVO> dishVOLists = (List<DishVO>) redisTemplate.opsForValue().get(key);
//        if (dishVOLists != null && dishVOLists.size() > 0) {
//            return dishVOLists;
//        }
        //可以用stream流设置
        //数据封装
        Dish dish = new Dish();
        dish.setCategoryId(canary_id);
        dish.setStatus(StatusConstant.ENABLE);//查询起售中的菜品

        //根据分类id查询菜品
        List<Dish> dishList = dishMapper.listByCategoryId(dish.getCategoryId());

        List<DishVO> dishVOList = new ArrayList<>();
        //永strem流做

//        map是映射的意思  将dishVOList映射成dishVO
        dishList.stream().map((x)->{
            DishVO dishVO=new DishVO();
            BeanUtils.copyProperties(x,dishVO);
            List<DishFlavor> byDishId = dishFlavorMapper.getByDishId(x.getId());
            dishVO.setFlavors(byDishId);
            dishVOList.add(dishVO);
            return dishVO;  //return到了第一行
        }).collect(Collectors.toList());

        //基础方法
//        for (Dish d : dishList) {
//            DishVO dishVO = new DishVO();
//            BeanUtils.copyProperties(d, dishVO);
//
//            //根据菜品id查询对应的口味
//            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());
//
//            dishVO.setFlavors(flavors);
//            dishVOList.add(dishVO);
//
//        }
        System.out.println(dishVOList);
        //添加到redis里方变下次查询
//        redisTemplate.opsForValue().set(key, dishVOList);
        return dishVOList;
    }


    /**
     * 添加一个新的菜品
     */
    @Override                         //全删
    @CacheEvict(cacheNames = "dish_",allEntries = true)//通过注解实现删除缓存
    public void add(DishDTO dto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        dish.setStatus(StatusConstant.ENABLE);
        //检查名字是否重复
        Dish dish1 = dishMapper.selectByName(dto.getName());
        if (dish1 != null) {
            throw new DishNameRepeatException(MessageConstant.DISH_NAME_HAS);
        }
        //添加一条菜品信息
        dishMapper.add(dish);
        //添加一条响应的口味信息
        //获得主键id
        Long id = dish.getId();
        //获得最喜欢的口味
        List<DishFlavor> flavors = dto.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            for (DishFlavor flavor : flavors) {
                //口味关联相应的菜品
                flavor.setDishId(id);
                //插入响应的口味
                dishFlavorMapper.add(flavor);

            }
        }
        //删除redis库里面缓存，来保证数据实时更新
//        String key = "dish_" + dto.getCategoryId();
//        cleanCache(key);

    }

    /**
     * 菜品分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageBean<DishVO> listByPage(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<DishVO> page = dishMapper.listByPage(dto);
        return new PageBean<>(page.getTotal(), page.getResult());
    }

    /**
     * 删除菜品
     *
     * @param ids
     */
    @Override
    @Transactional //开启事物 ！因为是要么都删，要么都不删
    @CacheEvict(cacheNames = "dish_",allEntries = true)//通过注解实现删除缓存
    public void delete(List<Long> ids) {
        long categoryId = 0;
        //判断当前菜品是否在出售
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            categoryId = dish.getCategoryId();
            if (dish.getStatus() == StatusConstant.ENABLE) {
                //抛出异常，事物回滚
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
            //判断当前菜品是否被套餐关联
            List<Long> setmealIds = setmealMapper.getSetmealIdsByDishId(id);
            if (setmealIds != null && setmealIds.size() > 0) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
            dishMapper.deleteById(id);

//           setmealMapper.deleteByDishId(id);   应不用改删除套餐呢？
            //删除口味表
            dishFlavorMapper.deleteByDishId(id);

        }
        //删除redis库里面缓存，来保证数据实时更新
//        String key = "dish_" +categoryId;
//        cleanCache(key);

    }

    /**
     * 根据id查找菜品
     *
     * @param id
     */
    @Override
    public DishVO getById(Long id) {
        Dish dish = dishMapper.getById(id);
        //根据id查出口味
        List<DishFlavor> byDishId = dishFlavorMapper.getByDishId(id);

        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(byDishId);
        return dishVO;
    }

    /**
     * 更新操作
     *
     * @param dish
     */
    @Override                       //全删
    @CacheEvict(cacheNames = "dish_",allEntries = true)//通过注解实现删除缓存
    public void update(DishDTO dish) {
        Dish dishUpdate = new Dish();
        BeanUtils.copyProperties(dish, dishUpdate);
        dishUpdate.setUpdateTime(LocalDateTime.now());
        //修改菜品信息
        dishMapper.update(dishUpdate);
        //删除原有口味
        dishFlavorMapper.deleteByDishId(dishUpdate.getId());
        //重新出入口味
        List<DishFlavor> flavors = dish.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dish.getId());
                dishFlavorMapper.add(flavor);
            }
        }
        //删除redis库里面缓存，来保证数据实时更新
//        String key = "dish_" +dish.getCategoryId();
//        cleanCache(key);

    }


    /**
     * @param status
     * @param id
     */
    @Override
    public void changeStatus(Integer status, Long id) {
        Dish dish = new Dish();
        dish.setStatus(status);
        dish.setId(id);
        dish.setUpdateTime(LocalDateTime.now());
        dishMapper.update(dish);
        //把相应的套餐停售了
        List<Long> longs = setmealDishMapper.selectSetmealIdByDishId(id);
        for (Long list : longs) {
            setmealMapper.
                    updateStatus(Setmeal.builder().id(list).status(0).build());
        }

    }

    /**
     * 通过菜品分类id查询
     *
     * @param id 菜品分类id
     * @return
     */
    @Override
    public List<Dish> listByCategoryId(Long id) {
        List<Dish> listByCategoryId = dishMapper.listByCategoryId(id);
        return listByCategoryId;
    }

//
//    /**
//     * 清理缓存数据
//     *
//     * @param pattern
//     */
//    public void cleanCache(String pattern) {
//        Set keys = redisTemplate.keys(pattern);
//        redisTemplate.delete(keys);
//    }


}
